<template>
  <div ref="echartsRef" :class="className" :style="{ height: height, width: width }" />
</template>

<script setup>
import * as echarts from "echarts";

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  dataArray: {
    type: Array,
    default: () => [],
  },
  className: {
    type: String,
    default: "chart",
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "300px",
  },
})

const pieTitle = props.title;
const dataArr = props.dataArray;
const className = props.className;
const width = props.width;
const height = props.height;

const echartsRef = ref(null);
let myChart = null;

onMounted(() => {
  if (echartsRef.value) {
    initChart(pieTitle, dataArr);
  }
});

watch(
  () => props.dataArray,
  (newValue) => {
    initChart(pieTitle, newValue);
  },
)

// 组件卸载前销毁图表，避免内存泄露
onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
});

function initChart(tmpTitle, tmpDataArr) {
  myChart = echarts.init(echartsRef.value, "macarons");
  myChart.setOption({
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    series: [
      {
        name: tmpTitle,
        type: "pie",
        roseType: "radius",
        radius: [10, 60],
        center: ["50%", "50%"],
        color: ["#5083f8", "#ffdb75", "#c5e573","#ca8622"],
        data: tmpDataArr,
        animationEasing: "cubicInOut",
        animationDuration: 1000,
      }
    ]
  });
  window.addEventListener("resize", () => {
    myChart.resize();
  });
}
</script>
